<template>
  <basic-container>
    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="tabClick">
      <el-tab-pane label="基本信息" name="info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="岗位名称" align="center">
            {{ position.name }}
          </el-descriptions-item>
          <el-descriptions-item label="岗位编号" align="center">
            {{ position.code }}
          </el-descriptions-item>
          <el-descriptions-item label="密级" align="center">
            {{ position.securityName }}
          </el-descriptions-item>
          <el-descriptions-item label="学习时长要求" align="center">
            {{ position.countRequireTimeHour }}小时
          </el-descriptions-item>
          <el-descriptions-item label="岗位职责" :span="2" align="center">
            {{ position.note }}
          </el-descriptions-item>
          <el-descriptions-item label="是否方向分支" :span="2" align="center">
            {{ position.isDirection ? '是' : '否' }}
          </el-descriptions-item>
          <el-descriptions-item v-for="itemTime in position.timeList" :key="itemTime.classificationId"
            :label="itemTime.classificationName" align="center">{{ itemTime.countRequireTimeHour
            }}小时</el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane label="岗位人员" name="people" v-if="!position.hasChild">
        <div>
          <el-button type="primary" icon="el-icon-plus" @click="peopleDialog = true">
            新增
          </el-button>
          <avue-crud :option="option" v-model:search="search" v-model:page="page" v-model="form"
            :table-loading="loading" :data="data" :before-open="beforeOpen" ref="crud" @row-del="rowDel"
            @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
            @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
            <template #product="{ row }">
              <div class="flex flex-wrap" v-if="row.checked">
                <el-input v-model="row.product" />
                <el-button type="primary" @click="setProduct(row)">修改</el-button>
              </div>
              <div class="flex flex-wrap" v-else>
                <el-tag class="mr5">{{ row.product }}</el-tag>
                <el-button type="primary" @click="row.checked = true">编辑</el-button>
              </div>
            </template>
            <template #menu="{ row }">
              <el-button link type="primary" icon="orange" @click="dismiss(row)">解聘</el-button>
            </template>
          </avue-crud>
        </div>
      </el-tab-pane>
      <el-tab-pane label="岗位知识" name="knowledge" v-if="!position.hasChild">
        <el-tabs v-model="activeTab" type="card" class="demo-tabs" @tab-click="changeTab">
          <el-tab-pane :label="item.name" :name="item.id" v-for="item in tabsData" :key="item.id">
            <div class="pt10">
              <el-button type="primary" icon="Paperclip" @click="openDirectionChoose">
                添加
              </el-button>
              <el-button type="danger" plain icon="el-icon-delete" @click="removeDirectionChoose">
                移除
              </el-button>
              <el-button type="info" plain icon="Memo" @click="deepDialog = true">
                设置学习程度
              </el-button>
              <span style="float: right">该类型累计时长：{{ countTime }}小时</span>
            </div>
            <div class="avue-crud">
              <el-table :data="tableDataTabsParent" @selection-change="selectionChange" border stripe>
                <el-table-column type="selection" width="55" />
                <el-table-column prop="index" label="序号" width="80" />
                <el-table-column prop="name" label="知识点">
                  <template #default="scope">
                    <el-tag style="cursor: pointer" @click="openDialog(scope)">
                      {{ scope.row.name }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="levelName" label="学习程度" />
                <el-table-column prop="securityName" label="密级" />
                <el-table-column prop="countTimeHour" label="课件时长" />
                <el-table-column prop="statusName" label="学习状态" />
              </el-table>
              <div class="mt10 flex flex-center">
                <el-pagination background layout="prev, pager, next" :total="page.total"
                  @current-change="currentChange" />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
      <el-tab-pane label="组卷设置" name="group" v-if="!position.hasChild">
        <group :tabsData="tabsData" :currentId="currentNode.data.id" ref="group"></group>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加人员弹窗 -->
    <el-dialog v-model="peopleDialog" width="1200" title="添加人员">
      <UserForm @close="close" />
    </el-dialog>

    <!-- 选择知识点弹窗 -->
    <el-dialog v-model="chooseKnowledgeDialog" width="1200" title="选择知识点">
      <div class="flex mt-20 mb10">
        <el-input v-model="knowledgeValue" placeholder="请输入知识点名称" class="mr10"></el-input>
        <el-button type="primary" icon="search" @click="onSearch">搜索</el-button>
        <el-button type="info" plain @click="onReset">重置</el-button>
      </div>

      <div class="avue-crud">
        <el-table :data="tableDataknowledge" @selection-change="selectionChange" border stripe>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="index" label="序号" width="80" align="center" />
          <el-table-column prop="name" label="知识点" width="300" align="center">
            <template #default="scope">
              <el-tag style="cursor: pointer" @click="openDialog(scope)">
                {{ scope.row.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="securityName" label="密级" width="80" align="center" />
          <el-table-column prop="countTimeHour" label="课件时长" width="120" align="center" />
          <el-table-column prop="note" label="简介" align="center" />
          <el-table-column prop="test" label="试题" align="center">
            <template #default="scope">
              <div>
                <el-tag style="cursor: pointer" v-for="item in website.knowledgeLevelLists" :key="item.value"
                  @click="gotoCourseware(item.value, scope)" class="mr5">{{ item.label }}</el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mt10 flex flex-center">
        <el-pagination background layout="prev, pager, next" :total="page.total" @current-change="currentChange1" />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="chooseKnowledgeDialog = false">取消</el-button>
          <el-button type="primary" @click="handleChooseKnowledge">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置学习程度弹窗 -->
    <el-dialog v-model="deepDialog" width="1200" title="设置学习程度">
      <el-radio-group v-model="knowledgeDeep">
        <el-radio v-for="item in website.knowledgeLevelLists" :key="item.value" :value="item.value" :label="item.value">
          {{ item.label }}
        </el-radio>
      </el-radio-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deepDialog = false">取消</el-button>
          <el-button type="primary" @click="setDeepDialog">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 方向分支弹窗 -->
    <el-dialog v-model="chooseDirectionDialog" width="1200" title="选择方向分支">
      <div class="flex align-center">
        <span class="text-e">是否岗位方向分支：</span>
        <el-select v-model="directionFZ" placeholder="请选择是否方向分支">
          <el-option :value="0" label="否"></el-option>
          <el-option :value="1" label="是"></el-option>
        </el-select>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="chooseDirectionDialog = false">取消</el-button>
          <el-button type="primary" @click="setPositionSequencesByChoose">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <Dialog :data="currentData" ref="child" @close="visible = false" />
  </basic-container>
</template>

<script>
import { getDetail as getPositionDetail } from '@/api/position/positionInstance';
import { getList, add, remove, update as userUpdate, dismiss } from '@/api/position/positionUser';
import { update } from '@/api/position/positionInstance';
import option from '../options/position';
import optionDir from '../options/positionDir';
import UserForm from './userForm.vue';
import {
  getTime,
  addKnowledge,
  getKnowledgeList,
  getKnowledgeLists,
  removeKnowledge,
  updateLevel,
} from '@/api/position/knowledgeClassification';
import {
  getDirList,
  getDirDetail,
  getDirListByInstance,
  removeDir,
  addDir,
  updateDir,
  getTabsTree,
} from '@/api/position/direction';
import courseWareDialog from './courseWareDialog.vue';
import Group from './group.vue';

export default {
  components: { UserForm, Dialog: courseWareDialog, Group },
  props: {
    currentNode: Object,
  },
  watch: {
    'currentNode.data.id': {
      handler(e) {
        this.getDetail();
      },
      immediate: true,
    },
  },
  mounted() {
    this.option.column[3].dicData = this.website.securityLists;
    this.optionDir.column[3].dicData = this.website.securityLists;
    console.log(666, this.currentNode);
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      knowledgeValue: '',
      selectionList: [],
      option: option,
      data: [],
      activeName: 'knowledge',
      descriptions: {},
      position: {},
      peopleDialog: false,
      selectUsers: [],
      tabsData: [],
      tableDataTabsParent: [],
      activeTab: '',
      countTime: '',
      chooseKnowledgeDialog: false,
      tableDataknowledge: [],
      deepDialog: false,
      knowledgeDeep: '',
      chooseDirectionDialog: false,
      directionFZ: 0,
      searchDir: {},
      pageDir: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      formDir: {},
      loadingDir: false,
      dataDir: [],
      optionDir,
      currentData: {
        data: {},
        form: {},
        crud: [],
      },
    };
  },
  methods: {
    setPositionSequencesByChoose() {
      update({
        id: this.position.positionInstanceId,
        hasChild: this.directionFZ,
      })
        .then(res => {
          this.$message.success('设置成功');
          this.getDetail();
          this.chooseDirectionDialog = false;
        })
        .catch(err => {
          this.$message.error('设置失败');
        });
    },
    removeDirectionChoose() {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const p = [];
        this.selectionList.forEach(item => {
          p.push(removeKnowledge(item.ids));
        });
        Promise.all(p).then(res => {
          this.$message.success('删除成功');
          const index = this.tabsData.findIndex(item => item.id == this.activeTab);
          this.changeTab({ index });
        });
      });
    },
    setDeepDialog() {
      const p = [];
      this.selectionList.forEach(item => {
        p.push(updateLevel(item.ids, this.knowledgeDeep));
      });
      Promise.all(p).then(res => {
        this.$message.success('设置成功');
        this.deepDialog = false;
        const index = this.tabsData.findIndex(item => item.id == this.activeTab);
        this.changeTab({ index });
      });
    },
    handleChooseKnowledge() {
      const p = [];
      this.selectionList.forEach(item => {
        p.push(addKnowledge(item.id, this.currentNode.data.id));
      });
      Promise.all(p).then(res => {
        this.$message.success('添加成功');
        this.chooseKnowledgeDialog = false;
        const index = this.tabsData.findIndex(item => item.id == this.activeTab);
        this.changeTab({ index });
      });
    },
    openDirectionChoose() {
      this.chooseKnowledgeDialog = true;
      getKnowledgeLists(
        { classificationId: this.activeTab, status: 1 },
        1,
        this.page.pageSize
      ).then(res => {
        this.page.total = res.data.data.total;
        this.tableDataknowledge = res.data.data.records.map((item, index) => {
          return {
            index: index + 1,
            ids: item.id,
            levelName: item.levelName,
            ...item,
          };
        });
      });
    },
    changeTab(e) {
      const index = e.index;
      const id = this.tabsData[index].id;

      getTime(this.currentNode.data.id, id).then(res => {
        this.countTime = res.data.data;
      });
      getKnowledgeList(this.currentNode.data.id, id, this.page.currentPage, this.page.pageSize).then(res => {
        this.page.total = res.data.data.total
        this.tableDataTabsParent = res.data.data.records.map((item, index) => {
          return {
            ...item.knowledgeVO,
            index: index + 1,
            ids: item.id,
            levelName: item.levelName,
            statusName: item.statusName,
          };
        });
      });
    },
    getTreeData() {
      getTabsTree().then(res => {
        this.tabsData = res.data.data;
        this.activeTab = this.tabsData[0].id;
        getKnowledgeList(this.currentNode.data.id, this.tabsData[0].id, this.page.currentPage, this.page.pageSize).then(res => {
          this.page.total = res.data.data.total
          this.tableDataTabsParent = res.data.data.records.map((item, index) => {
            return {
              ...item.knowledgeVO,
              index: index + 1,
              ids: item.id,
              levelName: item.levelName,
              statusName: item.statusName,
            };
          });
        });
        getTime(this.currentNode.data.id, this.activeTab).then(res => {
          this.countTime = res.data.data;
        });
      });
    },
    tabClick({ index }) {
      if (index == 3) {
        this.$refs.group.getDetail(this.position.parentId);
      }
    },
    close(selectUsers) {
      this.peopleDialog = false;
      const p = [];
      selectUsers.forEach(user => {
        p.push(
          add({
            positionInstanceId: this.currentNode.data.id,
            userId: user.id,
            product: user.product,
          })
        );
      });
      Promise.all(p)
        .then(res => {
          this.$message.success('添加成功');
          this.onLoad();
        })
        .catch(res => {
          this.$message.success('添加失败');
        });
    },
    securityLabel(security) {
      let securityObj = this.website.securityLists.find(item => item.value == security);
      return securityObj ? securityObj.label : security;
    },
    getDetail() {
      getPositionDetail(this.currentNode.data.id).then(res => {
        this.position = res.data.data.position;
        this.position.countRequireTimeHour = res.data.data.countRequireTimeHour;
        this.position.timeList = res.data.data.timeList;
        this.position.parentId = res.data.data.id;
        if (this.position.hasChild) {
          this.activeName = 'info';
        } else {
          this.getTreeData();
        }
        this.onLoad();
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.parentId);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    beforeOpen(done, type) {
      if (['edit'].includes(type)) {
        getPositionSequenceDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.form.sequenceId = this.currentNode.data.id;
          this.form.security = String(this.form.security);
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad();
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad();
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
    },
    currentChange1(currentPage) {
      getKnowledgeLists(
        { classificationId: this.activeTab, status: 1 },
        currentPage,
        this.page.pageSize
      ).then(res => {
        this.page.total = res.data.data.total;
        this.tableDataknowledge = res.data.data.records.map((item, index) => {
          return {
            index: index + 1,
            ids: item.id,
            levelName: item.levelName,
            ...item,
          };
        });
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      getKnowledgeList(this.currentNode.data.id, this.activeTab, this.page.currentPage, this.page.pageSize).then(res => {
        this.page.total = res.data.data.total
        this.tableDataTabsParent = res.data.data.records.map((item, index) => {
          return {
            ...item.knowledgeVO,
            index: index + 1,
            ids: item.id,
            levelName: item.levelName,
            statusName: item.statusName,
          };
        });
      });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;

    },
    refreshChange() {
      this.onLoad();
    },
    onLoad() {
      this.loading = true;
      if (!this.currentNode.data.id) {
        return;
      }
      getList(this.currentNode.data.id).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map(item => {
          return {
            ...item.user,
            product: item.product,
            parentId: item.id,
          };
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    openDialog(data) {
      this.currentData.data = data.row;
      this.$refs.child.open();
    },
    gotoCourseware(type, data) {
      sessionStorage.setItem('question', JSON.stringify({
        id: data.row.id,
        name: data.row.name,
        type,
      }))
      this.$router.push({
        path: '/question',
      });
    },
    setProduct(row) {
      row.checked = false;
      userUpdate({
        id: row.parentId,
        product: row.product,
      }).then(res => {
        this.$message.success('修改成功');
      });
    },
    onSearch() {
      getKnowledgeLists(
        { classificationId: this.activeTab, status: 1, name: this.knowledgeValue },
        this.page.currentPage,
        this.page.pageSize
      ).then(res => {
        this.page.total = res.data.data.total;
        this.tableDataknowledge = res.data.data.records.map((item, index) => {
          return {
            index: index + 1,
            ids: item.id,
            levelName: item.levelName,
            ...item,
          };
        });
      });
    },
    onReset() {
      this.knowledgeValue = '';
      getKnowledgeLists(
        { classificationId: this.activeTab, status: 1, name: this.knowledgeValue },
        this.page.currentPage,
        this.page.pageSize
      ).then(res => {
        this.page.total = res.data.data.total;
        this.tableDataknowledge = res.data.data.records.map((item, index) => {
          return {
            index: index + 1,
            ids: item.id,
            levelName: item.levelName,
            ...item,
          };
        });
      });
    },
    dismiss(row) {
      dismiss(row.parentId).then(res => {
        this.$message.success('解聘成功');
        this.$emit('refresh');
      });
    },
  },
};
</script>

<style>
.flex-wrap {
  flex-wrap: wrap;
  align-items: center;
}
</style>
